package com.cskaoyan.market.service.impl;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.db.domain.MarketUserExample;
import com.cskaoyan.market.db.mapper.MarketUserMapper;
import com.cskaoyan.market.service.MarketAdminUserService;
import com.cskaoyan.market.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class MarketAdminUserServiceImpl implements MarketAdminUserService {

    @Override
    public MarketUser list(int id) {

        // 获取mapper对象
        SqlSession session = MyBatisUtil.getSession();
        MarketUserMapper userMapper = session.getMapper(MarketUserMapper.class);

        // 获取example
        MarketUserExample userExample = new MarketUserExample();
        userExample.or();

        // 获取查询结果
        MarketUser marketUser = userMapper.selectByPrimaryKey(id);

        session.commit();
        session.close();

        return marketUser;
    }

    @Override
    public List<MarketUser> getUserPage(String username, String mobile, String page, String limit, String sort, String order) {
        SqlSession session = MyBatisUtil.getSession();

        MarketUserMapper userMapper = session.getMapper(MarketUserMapper.class);

        MarketUserExample userExample = new MarketUserExample();

        /**
         * 如果username和mobile不为空，需要拼接对应的条件
         */
        MarketUserExample.Criteria criteria = userExample.or();
        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (!StringUtils.isEmpty(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }

        userExample.setOrderByClause(sort + " " + order);

        // startPage()尽量和查询写到一起(紧邻)
        PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(limit));
        List<MarketUser> userList = userMapper.selectByExample(userExample);

        session.commit();
        session.close();

        return userList;
    }

    @Override
    public int updateMarkedUser(MarketUser marketUser) {
        SqlSession session = MyBatisUtil.getSession();
        MarketUserMapper userMapper = session.getMapper(MarketUserMapper.class);

        int line = userMapper.updateByPrimaryKey(marketUser);

        // System.out.println("更新行数:" + line);

        session.commit();
        session.close();

        return line;
    }
}
